package com.wangshuqi.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LoginFilter implements Filter {

    private FilterConfig _filterConfig = null;
    private String[] excludedUrlArray;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String excludedUrls = filterConfig.getInitParameter("excludedUrls");
        if (excludedUrls != null && !"".equals(excludedUrls)) {
            excludedUrlArray = excludedUrls.split(",|，");
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        boolean isExcluded = false;
        for (String page : excludedUrlArray) { //判断是否在过滤url之外
            String pathInfo = req.getServletPath();
            if (pathInfo.equals(page)) { // 如果路径是写入排除对象中
                isExcluded = true;
                break;
            }
        }
        if (isExcluded) {
            chain.doFilter(request, response);
            return;
        }
        if (req.getSession().getAttribute("username") == null) {
            resp.sendRedirect(req.getContextPath() + "/error.jsp");
        }
        chain.doFilter(request, response);
    }
}
